package info.maxhis.bn.renren;

import info.maxhis.bn.MainActivity;
import info.maxhis.bn.R;
import info.maxhis.entity.Friend;
import info.maxhis.service.FriendService;
import info.maxhis.util.SharedData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.renren.api.connect.android.AsyncRenren;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.RequestListener;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.exception.RenrenError;
import com.renren.api.connect.android.view.RenrenAuthListener;

/**
 * 人人网好友列表
 * @author iStar,2011-7-3
 *
 */
public class RenrenFriendListActivity extends Activity implements OnClickListener {
	public static String USER_FIELDS_1 = "name,birthday"; //"name,birthday,headurl"
	public static String USER_FIELDS_2 = "name,birthday,headurl"; //
	public static final int MESSAGE_DONE = 0;
	public static final int MESSAGE_ERROR = 1;
	public static final int MESSAGE_UPDATE_UI = 2; 
	public static final int MESSAGE_SAVE = 3;
	
	private ListView listView;
	private Context context;
	ArrayList<Boolean> selected = new ArrayList<Boolean>();
	List<Map<String, String>> data = null;
	ImageAdapter adapter = null;
	SharedData share;
	private FriendService fs;
	private String uids = "";
	private ProgressDialog progressDialog;
	private Renren renren;
	private AsyncRenren asyncRenren;
	private Resources rs;
	String userfields = USER_FIELDS_1;
	int count = 0;//添加到本地的数目
	int googleCnt = 0;//添加到Google Calendar的数目
	
	//将所有uids分组，每组10条
	ArrayList<String> uidArray = new ArrayList<String>();
	int index = 0;	// uidArray的当前组号
	int dataIndex = 0; // 标记data次序
	LinearLayout loadingLayout;//显示“加载中...”
	
	/**
	 * 设置布局显示为目标有多大就多大
	 */
	private LayoutParams WClayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);
	/**
	 * 设置布局显示目标最大化
	 */
	private LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.FILL_PARENT,
			LinearLayout.LayoutParams.FILL_PARENT);
	
	private ProgressBar progressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.activity_renren_friend_list);
		context = this;
		
		rs = getResources();
		share = new SharedData(context);
		fs = new FriendService(context);
		uids = share.getRenrenIds();
		renren = new Renren(share.getApiKey());
		renren.restorSessionKey(context);	//不添加会得不到数据
		asyncRenren = new AsyncRenren(renren);
		
		
		//没有登陆先登陆
		if (!renren.isSessionKeyValid()) {
			renren.authorize(this, new AuthListener());
			return ;
        }
		progressDialog = ProgressDialog.show(context, "请稍候", "正在获取人人网好友信息...");
		if (share.downloadRenrenHead()) {
			userfields = USER_FIELDS_2;
		}
		initIds();
		
		findViews();
		prepareData();
	}
	
	/**
	 * 获取数据
	 */
	private void prepareData() {
		if (uidArray.size()>0) {
			
			Bundle params = new Bundle();
			params.putString("method", "users.getInfo");
			params.putString("uids", uidArray.get(0));
			params.putString("fields", userfields);
			
			// 得到json数据,在RenrenRequestListener中发送完成消息，
			// 然后在handler中继续处理UI显示数据
			asyncRenren.requestJSON(params, new RenrenRequestListener());
			index ++;
		}
	}

	/**
	 * 初始化人人网好友的id列表
	 */
	public void initIds(){
		if (uids == null || "".equals(uids) || uids.contains("error")) {
			Thread t = new Thread(){
				public void run() {
					Bundle params = new Bundle();
	                params.putString("method", "friends.get");
	                uids = renren.requestJSON(params);
	                
	                if (uids != null) {
	                	//去掉JSON中的 []
	                	uids = uids.substring(1, uids.length()-1);
	                	//保存到缓存中
	                	share.saveRenrenIds(uids);
	                	
					}
				};
			};
			t.start();
			try {
				t.join(); //等待线程执行完
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//分组,10个一组
    	String[] array = uids.split(",");
    	StringBuilder sb = new StringBuilder();
    	for (int i = 0; i < array.length; i++) {
			sb.append(array[i]).append(",");
			if (i != 0 && ((i % 10 == 0) || (i == array.length-1))) {
				//去除最后一个 ,
				sb.deleteCharAt(sb.length()-1);
				//添加到id数组
				uidArray.add(sb.toString());
				//清空buffer
				sb.delete(0, sb.length());
			}
		}
	}

	
	
	/**
	 * 当ListView数据为空时显示提示信息
	 */
	private void onListViewEmpty() {
		TextView tv = (TextView) findViewById(R.id.on_renren_list_empty);
		tv.setText("暂无可导入的人人网好友");
		listView.setEmptyView(tv);
	}

	/**
	 * 得到所有控件
	 */
	private void findViews() {
		listView = (ListView) findViewById(R.id.renren_list);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		//保存到本地数据库
		case R.id.save_renren_btn:
			progressDialog = ProgressDialog.show(context, "请稍候", "正在添加...");
			new Thread(){
				public void run() {
					//添加到本地数据库
					Map<String, String> tmp;
					for (int i = 0; i < data.size(); i++) {
						tmp = data.get(i);
						if (selected.get(i)) {	
							String birthday = tmp.get("birthday");
							String[] births = null;
							Friend f = null;
							if (birthday != null && !birthday.equals("")) {
								births = birthday.split("-");
								f = new Friend(tmp.get("name"),
										Integer.parseInt(births[0])==0 ? 1980 : Integer.parseInt(births[0]),
										Integer.parseInt(births[1])==0 ? 1 : Integer.parseInt(births[1]),
										Integer.parseInt(births[2])==0 ? 1 : Integer.parseInt(births[2]));
							} else {
								// 若没有生日则设置成1980-1-1
								f = new Friend(tmp.get("name"), 1980, 1, 1);
							}
							String id = tmp.get("uid");
							f.setUid(id);
							boolean added = fs.addFriend(f);
							boolean toGoogle = fs.addToGoogle(f);
							if (share.downloadRenrenHead()) {
								//保存头像到本地，以uid作为头像文件名
								String url = tmp.get("headurl");
								fs.saveFriendHead(url, id);
							}
							if (added) {
								count ++;
								//删除该好友在uids中的记录
								if (uids.contains((id+","))) {
									//不是最后一个，同时删除 ,
									uids = uids.replaceAll((id+","), "");
								} else {
									uids = uids.replaceAll(id, "");
								}
							}
							if (toGoogle) {
								googleCnt ++;
							}
						}
					}
					//更新uids
					share.saveRenrenIds(uids);
					sendMsg(MESSAGE_SAVE);
				};
			}.start();
			
			break;
		 
		//全选
		case R.id.select_all_btn:
			Button selectAllButton = (Button) findViewById(R.id.select_all_btn);
			String selectAll = selectAllButton.getText().toString();
			String selectStr = getResources().getString(R.string.select_all);//全选
			if (selectStr.equals(selectAll)) {
				selectAllButton.setText(R.string.select_none);	//全不选
				for (int j = 0; j < selected.size(); j++) {
					selected.set(j, true);
				}
			} else {
				selectAllButton.setText(R.string.select_all);
				for (int j = 0; j < selected.size(); j++) {
					selected.set(j, false);
				}
			}
			//发送消息，刷新listview
			sendMsg(MESSAGE_UPDATE_UI);
			break;
			
		//取消
		case R.id.cancel_renren_btn:
			Intent intent = new Intent(context, MainActivity.class);
			startActivity(intent);
			finish();
			break;

		default:
			break;
		}
	}
	
	/**
	 * 解析Json数组
	 * @param json
	 * @return
	 */
	private List<Map<String, String>> parseFriendJson(String json) {
        List<Map<String, String>> datas = new ArrayList<Map<String, String>>();
        try {
            JSONArray friends = new JSONArray(json);
            
            for (int i = 0; i < friends.length(); i++) {
                Map<String, String> d = new HashMap<String, String>();
                Object obj = friends.get(i);
                JSONObject jobj = new JSONObject(obj.toString());
                String uid = jobj.getString("uid");
                //若已添加，则不予显示
                if (fs.friendExsited(uid)) {
					continue ;
				}
                d.put("birthday", jobj.getString("birthday"));
                d.put("name", jobj.getString("name"));
                d.put("uid", uid);
                if (share.downloadRenrenHead()) {
					d.put("headurl", jobj.getString("headurl"));
					//保存头像到本地
					fs.saveFriendHead(jobj.getString("headurl"), uid);
				}
                
				//记录次序
                d.put("index", "" + dataIndex++);
                datas.add(d);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return datas;
    }
	
	//刷新UI的handler
	private Handler handler = new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 继续完成更新ui的操作
			case MESSAGE_DONE:
				
				// 线性布局
				LinearLayout layout = new LinearLayout(context);
				// 设置布局 水平方向
				layout.setOrientation(LinearLayout.HORIZONTAL);
				// 进度条
				progressBar = new ProgressBar(context);
				// 进度条显示位置
				progressBar.setPadding(0, 0, 15, 0);

				layout.addView(progressBar, WClayoutParams);

				TextView textView = new TextView(context);
				textView.setText("加载中...");
				textView.setGravity(Gravity.CENTER_VERTICAL);

				layout.addView(textView, FFlayoutParams);
				layout.setGravity(Gravity.CENTER);

				loadingLayout = new LinearLayout(context);
				loadingLayout.addView(layout, WClayoutParams);
				loadingLayout.setGravity(Gravity.CENTER);
				
				listView.addFooterView(loadingLayout);
				
				for (int i = 0; i < data.size(); i++) {
					selected.add(false);
				}
				
				listView.setAdapter(adapter);
				listView.setOnItemClickListener(new ListViewListener());
				//滚动监听器
				listView.setOnScrollListener(new ListScrollListener());
				onListViewEmpty();
				
				progressDialog.dismiss();
				break;
				
			case MESSAGE_ERROR:
				onListViewEmpty();
				
				progressDialog.dismiss();
				break;
			
			case MESSAGE_UPDATE_UI:	//刷新ListView
//				listView.invalidate();
				adapter.notifyDataSetChanged();
				
				break;
				
			case MESSAGE_SAVE:	//保存完成
				progressDialog.dismiss();
				//没有选中任何一项
				if (count == 0) {
					share.showToast(R.string.none_selected);
					return ;
				}
				
				String notice = "！";
				if (share.isSyncGoogleCalendar()) {
					notice = "，并已同时添加到您的Google Calendar。";
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setMessage("导入成功，共添加了"+count+"个人人网好友信息" + notice).setCancelable(false)
						.setIcon(R.drawable.info).setTitle(rs.getString(R.string.notice))
						.setPositiveButton(rs.getString(R.string.confern), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								
								Intent it = new Intent(context, MainActivity.class);
								startActivity(it);
								RenrenFriendListActivity.this.finish();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
				break;

			default:
				break;
			}
		}
	};
	
	/**
	 * ListView监听器
	 * @author iStar,2011-7-2
	 *
	 */
	class ListViewListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			CheckBox checkBox = (CheckBox) view.findViewById(R.id.select);
			checkBox.toggle();
			TextView posView = (TextView) view.findViewById(R.id.pos);
			int pos = Integer.parseInt(posView.getText().toString());
			selected.set(pos, checkBox.isChecked());
		}
		
	}
	
	/**
	 * 获取好友信息
	 * @author iStar,2011-7-3
	 *
	 */
	class RenrenRequestListener implements RequestListener {

		@Override
		public void onComplete(String response) {
			data = parseFriendJson(response);
			adapter = new ImageAdapter(RenrenFriendListActivity.this, data);
			sendMsg(MESSAGE_DONE);
		}

		@Override
		public void onRenrenError(RenrenError renrenError) {
			Log.e("RenrenError", renrenError.toString());
			sendMsg(MESSAGE_ERROR);
		}

		@Override
		public void onFault(Throwable fault) {
			Log.e("RenrenError", fault.getMessage());
			sendMsg(MESSAGE_ERROR);
		}
		
	}
	
	/**
	 * 授权监听器
	 * @author iStar,2011-7-4
	 *
	 */
	class AuthListener implements RenrenAuthListener {

		@Override
		public void onComplete(Bundle values) {
			
//			initIds();
			
			Intent intent = new Intent(context, RenrenFriendListActivity.class);
			startActivity(intent);
			finish();
		}

		@Override
		public void onRenrenAuthError(RenrenAuthError renrenAuthError) {}

		@Override
		public void onCancelLogin() {
			Intent intent = new Intent(context, MainActivity.class);
			startActivity(intent);
			finish();
		}

		@Override
		public void onCancelAuth(Bundle values) {
			Intent intent = new Intent(context, MainActivity.class);
			startActivity(intent);
			finish();
		}
		
	}
	
	/**
	 * ListView 滚动监听器（动态加载数据）
	 * @author iStar,2011-7-5
	 *
	 */
	class ListScrollListener implements OnScrollListener {
		
		private boolean mTopFreeDisplayFoot = false;

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if(scrollState == OnScrollListener.SCROLL_STATE_IDLE && mTopFreeDisplayFoot) {
                if (index < uidArray.size()) {
					// display foot view loading
					Bundle params = new Bundle();
					params.putString("method", "users.getInfo");
					params.putString("uids", uidArray.get(index++));
					params.putString("fields", userfields);
					String json = renren.requestJSON(params);
					List<Map<String, String>> more = parseFriendJson(json);
					for (int i = 0; i < more.size(); i++) {
						selected.add(false);
					}
					data.addAll(more);
					adapter.notifyDataSetChanged();
					
					if (index == uidArray.size()) {
						//关闭  加载中...
						RenrenFriendListActivity.this.runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
//								loadingLayout.setVisibility(View.GONE);
								listView.removeFooterView(loadingLayout);
							}
						});
					}
				} 
            }  
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// reach bottom of the ListView
			if(firstVisibleItem + visibleItemCount >= totalItemCount){ 
				mTopFreeDisplayFoot = true;
			} else {
				mTopFreeDisplayFoot = false;
			}
		}
		
	}
	
	/**
	 * 向handler发送消息
	 * @param what msg.what
	 */
	void sendMsg(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}
}

